//
//  AVGDataList.cpp
//  Chart
//
//  Created by CaoJun on 13-6-6.
//
//

#include "AVGDataList.h"
#include <vector>

using namespace ytx;
using namespace std;


AVGDataList *AVGDataList::instance(NULL);


AVGDataList::AVGDataList(vector<Metal> & metalList, int spacing): quotationType(LineType::LAVG)
{
    create(metalList);
}

void AVGDataList::create(vector<Metal> & metalList)
{
    // TODO: use const_iterator instead of iterator
    for (vector<Metal>::iterator it = metalList.begin(); it != metalList.end(); ++it) {
        Metal &metal = *it;
        AVGData *avgData = new AVGData(metal.getId(),metal.getCurrentDate(), metal.getMarketType(), metal.getToFix(), metal.getName(), metal.getNickname(), metal.getOpenTime(), metal.getCloseTime(), metal.getDataSum(), metal.isHasVolume(), metal.getTimeString(), metal.getRow(), metal.getColumn(), metal.getRestTime());
        avgData->setIndexConfig(metal.getIndexConfig());
        
        vector<pair<YTXTime, YTXTime> > tradeTime = avgData->getRestTime();
        YTXTime currentDay = YTXTime(metal.getCurrentDate());
        int dd = 0;
        if (metal.getStepDay() == 1) {// 跨天时数据修正
            long dd1 = currentDay.toSeconds();
            long dd2 = YTXTime(YTXTime(metal.getOpenTime()).toStringYYYYMMdd()).toSeconds();
            dd = (int)((dd1 - dd2) / 60 / 60 / 24) + 1 - metal.getStepDay();
        }
        
        for (vector< pair<YTXTime, YTXTime> >::iterator it = tradeTime.begin(); it != tradeTime.end(); it++) {
            // 跨天
            YTXTime & t1 = (*it).first;
            t1 = ensureTime(t1, avgData->getOpenTime());
            YTXTime & t2 = (*it).second;
            t2 = ensureTime(t2, t1);
            
            int du = (int)((t2.toSeconds() - t1.toSeconds()) / 60);
            for (int i = 1; i <= du; i++) {
                avgData->dateRuler.push_back((t1 + minutes(i) + days(dd)).toStringGMT8YYYYMMddHHmmss());
            }
        }
        
        set(avgData);
    }
}

YTXTime AVGDataList::ensureTime(YTXTime t1, YTXTime earlisetDate)
{
    if (t1.toSeconds() < earlisetDate.toSeconds()) {
        t1 = t1 + days(1);
    }
    return t1;
}


AVGDataList::~AVGDataList()
{

}

AVGData *AVGDataList::get(string id)
{
    return (AVGData *)QuotationList::get(id, quotationType);
}

AVGDataList *AVGDataList::getInstance(vector<Metal> & metalList, int spacing)
{
    if(AVGDataList::instance == NULL) {
        AVGDataList::instance = new AVGDataList(metalList, spacing);
    }
    return AVGDataList::instance;
}

AVGDataList *AVGDataList::getInstance()
{
    return AVGDataList::instance;
}
